package com.ccs.onlinemusic.controller;


import com.ccs.onlinemusic.model.Music;
import com.ccs.onlinemusic.model.User;
import com.ccs.onlinemusic.server.MusicServer;
import com.ccs.onlinemusic.tools.Constant;
import com.ccs.onlinemusic.tools.ResponseBodyMessage;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/music")
public class MusicController {

    private String SAVE_PATH="D:/musicLoad/";
//    private String SAVE_PATH_NEW="D:/music/";

    @Autowired
    private MusicServer musicServer;
    @RequestMapping("/upload")
    public ResponseBodyMessage<Boolean> insertMusic(@RequestParam String singer
                                                    , @RequestParam("filename") MultipartFile file
                                                    , HttpServletRequest request
                                                    , HttpServletResponse req ) throws IOException {
        //没有session则不创建
        HttpSession httpSession=request.getSession(false);
        if(httpSession==null || httpSession.getAttribute(Constant.USERINFO_SESSION_KEY)==null){
            System.out.println("没有登录");
            return new ResponseBodyMessage<>(-1,"没有登录",false);
        }

        String filenameAndType=file.getOriginalFilename();
        log.info("filenameAndType--->", filenameAndType);
        String path=SAVE_PATH + filenameAndType;

        File dest=new File(path);
        System.out.println("dest->" + path);
        log.info("dest->",dest.getPath());

        if(!dest.exists()){
            dest.mkdir();
        }

        try {
            file.transferTo(dest);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        int index=filenameAndType.lastIndexOf(".");
        String title=filenameAndType.substring(0,index);

        SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
        String time=sf.format(new Date());

        String url="/musicLoad/get?path="+title;

        User user=(User)httpSession.getAttribute(Constant.USERINFO_SESSION_KEY);
        int userId=user.getId();
        int ret= musicServer.insert(title,singer,time,url,userId);
        if(ret==1){
            req.sendRedirect("list.html");
            return new ResponseBodyMessage<>(0,"数据库上传成功",true);
        }else{
            return new ResponseBodyMessage<>(-1,"数据库上传失败",false);
        }

    }


    @RequestMapping("/get")
    public ResponseEntity<Object> get(String path){
        //创建新的文件（路径名＋文件名）
        File file =new File(SAVE_PATH + path);
        //创建返回的数组（初始化为空）
        byte [] a=null;
        try {
            //将文件字符串赋值到数组中
            a= Files.readAllBytes(file.toPath());
            if(a==null){
                //如果为空 返回400
                return ResponseEntity.badRequest().build();
            }
            //正常 返回200
            return ResponseEntity.ok(a);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/delete")
    public ResponseBodyMessage<Boolean> deleteMusicById(@RequestParam String id){
        //获取删除的id对应的music
        int iid=Integer.parseInt(id);
        Music music=musicServer.findMusicById(iid);
        //如果该音乐不存在
        if(music==null){
            return new ResponseBodyMessage<>(-1,"没有你要删除的音乐",false);
        }
        //如果该音乐存在则
        int ret=musicServer.deleteMusicById(iid);
        //如果删除成功
        if(ret==1){
            //删除服务器目录下对应文件
            int index=music.getUrl().lastIndexOf("=");
            String filename=music.getUrl().substring(index+1);
            File file=new File(SAVE_PATH + "/" + filename + ".mp3");
            System.out.println("此时的路径为" + file.getPath());

            if(file.delete()){
                return new ResponseBodyMessage<>(0,"删除服务器音乐成功",true);
            }else{
                return new ResponseBodyMessage<>(-1,"删除服务器音乐失败",false);
            }
        }else{
            return new ResponseBodyMessage<>(-1,"删除数据库音乐失败",false);
        }
    }

    @RequestMapping("/deleteSel")
    public ResponseBodyMessage<Boolean> deleteSelMusic(@RequestParam("id[]") List<Integer> id ){
        //定义删除的数量 如果数量与ip数量相同 则全部删除成功
        int sum=0;
        //遍历循环删除音乐
        for(int i=0;i<id.size();i++){
            //获取该id的音乐
            Music music =musicServer.findMusicById(id.get(i));
            //删除该id的音乐
            int ret= musicServer.deleteMusicById(id.get(i));
            //如果删除成功
            if(ret==1){
                //删除服务器上的数据
                int index=music.getUrl().lastIndexOf("=");
                String filename=music.getUrl().substring(index+1);
                //获取该文件
                File file=new File(SAVE_PATH + "//" + filename + ".mp3");
                //如果删除成功
                if(file.delete()){
                    sum+=ret;
                }else{
                    return new ResponseBodyMessage<>(-1,"删除服务器的音乐失败",false);
                }
            }else{
                return new ResponseBodyMessage<>(-1,"删除数据库的音乐失败",false);
            }
        }
        if(sum==id.size()){
            return new ResponseBodyMessage<>(0,"批量删除成功",true);
        }else{
            return new ResponseBodyMessage<>(-1,"批量删除失败",false);
        }
    }


    @RequestMapping("/findMusic")
    public ResponseBodyMessage<List<Music>> findMusic(@RequestParam(required = false) String musicName){
        //初始化返回的音乐
        List<Music> listMusic=null;

        if (musicName!=null){
            listMusic=musicServer.findMusicByMusicName(musicName);
        }else{
            listMusic=musicServer.findMusic();
        }

        return new ResponseBodyMessage<List<Music>>(0,"查询到的音乐：",listMusic);
    }




//    @RequestMapping("/upload")
//    public ResponseBodyMessage<Boolean> insertMusic(@RequestParam String singer,@RequestParam MultipartFile file,
//                                                    HttpServletRequest request){
//        //检查是否登录
//        HttpSession httpSession=request.getSession(false);
//        if(httpSession==null){
//            log.info("没有登录",httpSession);
//            System.out.println("没有登录");
//            return new ResponseBodyMessage<>(-1,"请登录后上传",false);
//        }
//
//        String filenameAndType= file.getContentType();
//
//        String path=SAVE_PATH_NEW;
//
//        File dest=new File(path);
//        log.info("dest->",dest);
//
//        if(!dest.exists()){
//            dest.mkdir();
//        }
//
//        try {
//            file.transferTo(dest);
////            return new ResponseBodyMessage<>(0,"上传成功",true);
//        } catch (IOException e) {
//            log.info("音乐上传失败");
//            throw new RuntimeException(e);
//        }
//
//        //数据库的上传
//        //1.准备数据  2.调用insert
//
//        //获取歌名（先获取点号位置，再去0-点号位置的字符串）
//        int index=filenameAndType.lastIndexOf(".");
//        String title=filenameAndType.substring(0,index);
//
//        //获得关于音乐的其他信息
//        //id
//        User user=(User)httpSession.getAttribute(Constant.USERINFO_SESSION_KEY);
//        int userId= user.getId();
//
//        //播放音乐
//        String url="/CloudMusic?path="+title;
//
//        //时间
//        SimpleDateFormat sf= new SimpleDateFormat("yyyy-MM-dd");
//        String time=sf.format(new Date());
//
//
//
//        try {
//            int ret=0;
//            ret= musicServer.insert(title,singer,time,url,userId);
//            if(ret==1){
//                return new ResponseBodyMessage<>(0,"数据库上传成功",true);
//            }else{
//                return new ResponseBodyMessage<>(-1,"数据库上传失败",false);
//            }
//        }catch (BindingException e){
//            dest.delete();
//            return new ResponseBodyMessage<>(-1,"数据库上传失败",false);
//        }
//
//
//    }
}
